import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:go_router/go_router.dart';
import '../models/question.dart';
import '../services/database_service.dart';
import 'dart:developer' as developer;
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';


class AddEditQuestionScreen extends StatefulWidget {
  final String questionType;
  final int? questionId;
  
  const AddEditQuestionScreen({
    super.key, 
    required this.questionType, 
    this.questionId,
  });

  @override
  State<AddEditQuestionScreen> createState() => _AddEditQuestionScreenState();
}

class _AddEditQuestionScreenState extends State<AddEditQuestionScreen> {
  final _formKey = GlobalKey<FormState>();
  final _questionController = TextEditingController();
  final _optionAController = TextEditingController();
  final _optionBController = TextEditingController();
  final _optionCController = TextEditingController();
  final _optionDController = TextEditingController();
  final _correctAnswerController = TextEditingController();
  final _explanationController = TextEditingController();
  
  // 图片路径状态变量
  String? _questionImagePath;
  String? _optionAImagePath;
  String? _optionBImagePath;
  String? _optionCImagePath;
  String? _optionDImagePath;
  String? _explanationImagePath;
  final _keyPointController = TextEditingController(); // 添加考点控制器
  // 添加分类控制器
  final _categoryController = TextEditingController();
  String _selectedCategory = ''; // 选中的分类
  List<String> _categories = []; // 所有可用分类
  List<String> _keyPoints = []; // 所有可用考点
  
  bool get isEditing => widget.questionId != null;
  bool _isLoading = false;
  Question? _question;
  
  String get questionTypeTitle {
    switch (widget.questionType) {
      case 'politics':
        return '时政题目';
      case 'common_sense':
        return '常识判断';
      case 'verbal_comprehension':
        return '言语理解与表达';
      case 'quantitative_relation':
        return '数量关系';
      case 'logical_reasoning':
        return '判断推理';
      case 'data_analysis':
        return '资料分析';
      default:
        return '题目';
    }
  }
  
  @override
  void initState() {
    super.initState();
    // 确保先初始化分类和考点，再加载题目
    _initializeData();
  }
  
  // 初始化数据
  Future<void> _initializeData() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      // 先加载分类和考点
      await Future.wait([
        _loadCategories(),
        _loadKeyPoints(),
      ]);
      
      // 再加载题目
      if (isEditing) {
        await _loadQuestion();
      } else {
        // 对于新建题目，不设置默认分类
        // 移除默认分类设置
        // _categoryController.text = questionTypeTitle;
      }
      
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      developer.log('初始化数据失败: $e', error: e);
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('初始化数据失败: $e');
    }
  }
  
  // 加载所有分类
  Future<void> _loadCategories() async {
    try {
      final databaseService = DatabaseService();
      await databaseService.init();
      
      // 获取所有题目
      final questions = await databaseService.questionRepository.getAllQuestions();
      
      // 提取所有不重复的分类
      final categories = questions.map((q) => q.category).toSet().toList();
      
      // 确保当前题目类型在列表中
      if (!categories.contains(questionTypeTitle)) {
        categories.add(questionTypeTitle);
      }
      
      setState(() {
        _categories = categories;
        // 移除默认选中当前题目类型
        // _selectedCategory = questionTypeTitle;
      });
    } catch (e) {
      developer.log('加载分类失败: $e', error: e);
    }
  }
  
  // 加载所有考点
  Future<void> _loadKeyPoints() async {
    try {
      final databaseService = DatabaseService();
      await databaseService.init();
      
      // 获取所有题目
      final questions = await databaseService.questionRepository.getAllQuestions();
      
      // 提取所有不重复的考点
      final keyPoints = questions.map((q) => q.keyPoint).where((k) => k.isNotEmpty).toSet().toList();
      
      setState(() {
        _keyPoints = keyPoints;
      });
    } catch (e) {
      developer.log('加载考点失败: $e', error: e);
    }
  }
  
  Future<void> _loadQuestion() async {
    if (isEditing) {
      try {
        setState(() {
          _isLoading = true;
        });
        
        // 初始化数据库
        final databaseService = DatabaseService();
        await databaseService.init();
        
        // 加载题目数据
        _question = await databaseService.questionRepository.getQuestionById(widget.questionId!);
        
        if (_question != null) {
          _questionController.text = _question!.question;
          _optionAController.text = _question!.optionA;
          _optionBController.text = _question!.optionB;
          _optionCController.text = _question!.optionC;
          _optionDController.text = _question!.optionD;
          _correctAnswerController.text = _question!.correctAnswer;
          _explanationController.text = _question!.explanation;
          _keyPointController.text = _question!.keyPoint;
          _categoryController.text = _question!.category; // 设置分类控制器的文本
          
          // 加载图片路径
          _questionImagePath = _question!.questionImageUrl;
          _optionAImagePath = _question!.optionAImageUrl;
          _optionBImagePath = _question!.optionBImageUrl;
          _optionCImagePath = _question!.optionCImageUrl;
          _optionDImagePath = _question!.optionDImageUrl;
          _explanationImagePath = _question!.explanationImageUrl;
          
          setState(() {
            _selectedCategory = _question!.category;
          });
        }
        
        setState(() {
          _isLoading = false;
        });
      } catch (e) {
        developer.log('加载题目失败: $e', error: e);
        setState(() {
          _isLoading = false;
        });
        _showErrorSnackBar('加载题目失败: $e');
      }
    }
  }
  
  @override
  @override
  void dispose() {
    _questionController.dispose();
    _optionAController.dispose();
    _optionBController.dispose();
    _optionCController.dispose();
    _optionDController.dispose();
    _correctAnswerController.dispose();
    _explanationController.dispose();
    _keyPointController.dispose(); // 释放考点控制器
    _categoryController.dispose(); // 释放分类控制器
    super.dispose();
  }
  
  // 获取存储路径的方法
  Future<String> _getStoragePath() async {
    // 检查是否为桌面平台
    if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
      // 桌面平台使用固定路径
      return 'D:\\000\\my-web\\学习宝库\\图片\\题目';
    }
    
    // 移动平台处理
    if (Platform.isAndroid) {
      final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      final AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        throw Exception('需要存储权限才能保存图片');
      }
      
      // 获取存储目录
      Directory? directory;
      try {
        // 尝试获取外部存储目录
        directory = await getExternalStorageDirectory();
        if (directory == null) {
          throw Exception('无法获取外部存储目录');
        }
        
        // 构建路径：Download/考试宝/图片/题目
        String basePath = directory.path;
        // 如果路径包含Android/data，则需要回退到外部存储根目录
        if (basePath.contains('Android/data')) {
          List<String> paths = basePath.split('/');
          int index = paths.indexOf('Android');
          if (index > 0) {
            // 回退到外部存储根目录
            basePath = paths.sublist(0, index).join('/');
          }
        }
        
        return path.join(basePath, 'Download', '学习宝库', '图片', '题目');
      } catch (e) {
        print('获取存储路径失败: $e');
        // 如果无法获取外部存储，则使用应用内部存储
        directory = await getApplicationDocumentsDirectory();
        return path.join(directory.path, 'Download', '学习宝库', '图片', '题目');
      }
    } else if (Platform.isIOS) {
      // iOS平台使用应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '题目');
    } else {
      // 其他平台使用临时目录
      final directory = await getTemporaryDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '题目');
    }
  }
  
  // 选择图片的方法
  Future<void> _pickImage(String type) async {
    try {
      // 检查是否在Web平台
      if (kIsWeb) {
        // Web平台不支持本地文件选择，直接打开URL输入对话框
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Web平台不支持本地图片，请输入图片URL'),
            backgroundColor: Colors.orange,
          ),
        );
        // 打开URL输入对话框
        _showImageUrlInputDialog(type);
        return;
      }
      
      // 移动平台处理方式
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      
      if (image != null) {
        // 获取存储路径
        final String baseDir = await _getStoragePath();
        String moduleDir;
        
        // 根据平台处理路径
        if (Platform.isWindows) {
          // Windows平台使用反斜杠
          moduleDir = '$baseDir\\${widget.questionType}';
        } else {
          // 其他平台使用正斜杠
          moduleDir = path.join(baseDir, widget.questionType);
        }
        
        // 确保目录存在
        final directory = Directory(moduleDir);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
        
        final fileName = path.basename(image.path);
        final String savedPath = Platform.isWindows 
            ? '$moduleDir\\$fileName' 
            : path.join(moduleDir, fileName);
        final savedImage = await File(image.path).copy(savedPath);
        
        print('图片已保存到: ${savedImage.path}'); // 添加日志以便调试
        
        setState(() {
          switch (type) {
            case 'question':
              _questionImagePath = savedImage.path;
              break;
            case 'optionA':
              _optionAImagePath = savedImage.path;
              break;
            case 'optionB':
              _optionBImagePath = savedImage.path;
              break;
            case 'optionC':
              _optionCImagePath = savedImage.path;
              break;
            case 'optionD':
              _optionDImagePath = savedImage.path;
              break;
            case 'explanation':
              _explanationImagePath = savedImage.path;
              break;
          }
        });
      }
    } catch (e) {
      print('选择图片失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('选择图片失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
  
  // 显示图片URL输入对话框
  void _showImageUrlInputDialog(String type) {
    final TextEditingController urlController = TextEditingController();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('输入图片URL'),
        content: TextField(
          controller: urlController,
          decoration: const InputDecoration(
            hintText: 'https://example.com/image.jpg',
            labelText: '图片URL',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final url = urlController.text.trim();
              if (url.isNotEmpty) {
                setState(() {
                  switch (type) {
                    case 'question':
                      _questionImagePath = url;
                      break;
                    case 'optionA':
                      _optionAImagePath = url;
                      break;
                    case 'optionB':
                      _optionBImagePath = url;
                      break;
                    case 'optionC':
                      _optionCImagePath = url;
                      break;
                    case 'optionD':
                      _optionDImagePath = url;
                      break;
                    case 'explanation':
                      _explanationImagePath = url;
                      break;
                  }
                });
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  // 构建图片显示组件
  Widget _buildImageWidget(String imagePath, bool isNetworkImage, bool isLocalFilePath) {
    // 网络图片
    if (isNetworkImage) {
      return Image.network(
        imagePath,
        fit: BoxFit.cover,
        height: 100,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return const Center(child: CircularProgressIndicator());
        },
        errorBuilder: (context, error, stackTrace) => Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.error, color: Colors.red),
            const SizedBox(height: 4),
            const Text(
              '加载失败',
              style: TextStyle(fontSize: 12, color: Colors.red),
            ),
          ],
        ),
      );
    }
    
    // 本地文件路径 - 在Web平台上不支持
    if (isLocalFilePath) {
      if (kIsWeb) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.warning_amber_rounded, color: Colors.orange.shade700),
            const SizedBox(height: 4),
            const Text(
              '本地图片在Web中不可用',
              style: TextStyle(fontSize: 12, color: Colors.orange),
              textAlign: TextAlign.center,
            ),
          ],
        );
      } else {
        // 在移动平台上显示本地文件
        return Image.file(
          File(imagePath),
          fit: BoxFit.cover,
          height: 100,
          errorBuilder: (context, error, stackTrace) => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.error, color: Colors.red),
              const SizedBox(height: 4),
              Text(
                '加载失败: $error',
                style: const TextStyle(fontSize: 12, color: Colors.red),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        );
      }
    }
    
    // 未知类型
    return const Text('无效的图片路径');
  }
  
  // 图片预览组件
  Widget _buildImagePreview(String? imagePath, String type) {
    // 如果图片路径为空，则只显示添加图片按钮
    if (imagePath == null || imagePath.isEmpty) {
      return ElevatedButton.icon(
        icon: const Icon(Icons.image),
        label: const Text('添加图片'),
        onPressed: () => _pickImage(type),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.grey[200],
          foregroundColor: Colors.black87,
        ),
      );
    }
    
    // 检查是否是网络图片URL
    bool isNetworkImage = imagePath.startsWith('http://') || imagePath.startsWith('https://');
    
    // 检查是否是本地文件路径
    bool isLocalFilePath = imagePath.startsWith('/') || 
                          RegExp(r'^[A-Za-z]:\\').hasMatch(imagePath) || 
                          imagePath.startsWith('c:/') || 
                          imagePath.startsWith('C:/') ||
                          imagePath.contains(':\\Users\\') ||
                          imagePath.contains(':/Users/') ||
                          imagePath.contains('/Users/') ||
                          imagePath.contains('/Documents/');
    
    return Column(
      children: [
        Container(
          height: 100,
          width: double.infinity,
          margin: const EdgeInsets.only(bottom: 8),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Stack(
            children: [
              Center(
                child: _buildImageWidget(imagePath, isNetworkImage, isLocalFilePath),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: IconButton(
                  icon: const Icon(Icons.close, color: Colors.red),
                  onPressed: () {
                    setState(() {
                      switch (type) {
                        case 'question':
                          _questionImagePath = null;
                          break;
                        case 'optionA':
                          _optionAImagePath = null;
                          break;
                        case 'optionB':
                          _optionBImagePath = null;
                          break;
                        case 'optionC':
                          _optionCImagePath = null;
                          break;
                        case 'optionD':
                          _optionDImagePath = null;
                          break;
                        case 'explanation':
                          _explanationImagePath = null;
                          break;
                      }
                    });
                  },
                ),
              ),
            ],
          ),
        ),
        // 显示图片路径
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(4),
            border: Border.all(color: Colors.grey[300]!),
          ),
          child: Text(
            '路径: $imagePath',
            style: const TextStyle(fontSize: 12),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        const SizedBox(height: 8),
        ElevatedButton.icon(
          icon: const Icon(Icons.image),
          label: Text(imagePath == null ? '添加图片' : '更换图片'),
          onPressed: () => _pickImage(type),
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.grey[200],
            foregroundColor: Colors.black87,
          ),
        ),
      ],
    );
  }
  
  Future<void> _saveQuestion() async {
    if (_formKey.currentState!.validate()) {
      try {
        setState(() {
          _isLoading = true;
        });
        
        // 初始化数据库
        final databaseService = DatabaseService();
        await databaseService.init();
        
        final now = DateTime.now().millisecondsSinceEpoch;
        
        // 创建题目对象
        final question = Question(
          id: isEditing ? _question?.id : null,
          question: _questionController.text,
          questionImageUrl: _questionImagePath,
          optionA: _optionAController.text,
          optionAImageUrl: _optionAImagePath,
          optionB: _optionBController.text,
          optionBImageUrl: _optionBImagePath,
          optionC: _optionCController.text,
          optionCImageUrl: _optionCImagePath,
          optionD: _optionDController.text,
          optionDImageUrl: _optionDImagePath,
          correctAnswer: _correctAnswerController.text,
          explanation: _explanationController.text,
          explanationImageUrl: _explanationImagePath,
          category: _categoryController.text, // 使用分类输入框的文本
          keyPoint: _keyPointController.text, // 使用考点输入框的文本
          difficulty: isEditing ? _question!.difficulty : 1, // 设置难度，编辑时保留原难度，新增时使用默认值
          tags: isEditing ? _question!.tags : '', // 设置标签，编辑时保留原标签，新增时使用默认值
          created_at: isEditing ? _question!.created_at : now,
          updated_at: now,
          type: isEditing ? _question!.type : widget.questionType, // 设置题目类型，使用传入的questionType而不是默认值
        );
        
        // 保存题目
        if (isEditing) {
          await databaseService.questionRepository.updateQuestion(question);
          _showSuccessSnackBar('题目更新成功');
        } else {
          await databaseService.questionRepository.addQuestion(question);
          _showSuccessSnackBar('题目添加成功');
        }
        
        setState(() {
          _isLoading = false;
        });
        
        // 返回题目列表页面并传递刷新标志
        if (mounted) {
          Navigator.pop(context, true); // 返回并传递刷新标志
        }
      } catch (e) {
        developer.log('保存题目失败: $e', error: e);
        setState(() {
          _isLoading = false;
        });
        _showErrorSnackBar('保存题目失败: $e');
      }
    }
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(isEditing ? '编辑$questionTypeTitle' : '添加$questionTypeTitle'),
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // 分类输入
                    TextFormField(
                      controller: _categoryController,
                      decoration: const InputDecoration(
                        labelText: '分类',
                        border: OutlineInputBorder(),
                        hintText: '请输入分类',
                      ),
                      onChanged: (value) {
                        setState(() {
                          _selectedCategory = value;
                          if (_categoryController.text != value) {
                            _categoryController.text = value;
                          }
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    
                    // 考点输入
                    TextFormField(
                      controller: _keyPointController,
                      decoration: InputDecoration(
                        labelText: '考点',
                        border: const OutlineInputBorder(),
                        hintText: '请输入考点',
                        suffixIcon: _keyPoints.isNotEmpty
                            ? PopupMenuButton<String>(
                                icon: const Icon(Icons.arrow_drop_down),
                                onSelected: (String value) {
                                  setState(() {
                                    // 确保_keyPointController.text与输入值同步
                                    if (_keyPointController.text != value) {
                                      _keyPointController.text = value;
                                    }
                                  });
                                },
                                itemBuilder: (BuildContext context) {
                                  return _keyPoints.map<PopupMenuItem<String>>((String value) {
                                    return PopupMenuItem<String>(
                                      value: value,
                                      child: Text(value),
                                    );
                                  }).toList();
                                },
                              )
                            : null,
                      ),
                      // 添加onChanged事件处理，确保用户直接输入的内容能够正确保存
                      onChanged: (value) {
                        setState(() {
                          // 确保_keyPointController.text与输入值同步
                          if (_keyPointController.text != value) {
                            _keyPointController.text = value;
                          }
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    
                    // 题目内容
                    TextFormField(
                      controller: _questionController,
                      decoration: const InputDecoration(
                        labelText: '题目内容',
                        border: OutlineInputBorder(),
                        hintText: '请输入题目内容',
                      ),
                      maxLines: 5,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入题目内容';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),
                    
                    // 题目图片
                    _buildImagePreview(_questionImagePath, 'question'),
                    const SizedBox(height: 16),
                    
                    // 选项A
                    TextFormField(
                      controller: _optionAController,
                      decoration: const InputDecoration(
                        labelText: '选项A',
                        border: OutlineInputBorder(),
                        hintText: '请输入选项A',
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入选项A';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),
                    
                    // 选项A图片
                    _buildImagePreview(_optionAImagePath, 'optionA'),
                    const SizedBox(height: 16),
                    
                    // 选项B
                    TextFormField(
                      controller: _optionBController,
                      decoration: const InputDecoration(
                        labelText: '选项B',
                        border: OutlineInputBorder(),
                        hintText: '请输入选项B',
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入选项B';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),
                    
                    // 选项B图片
                    _buildImagePreview(_optionBImagePath, 'optionB'),
                    const SizedBox(height: 16),
                    
                    // 选项C
                    TextFormField(
                      controller: _optionCController,
                      decoration: const InputDecoration(
                        labelText: '选项C',
                        border: OutlineInputBorder(),
                        hintText: '请输入选项C',
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入选项C';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),
                    
                    // 选项C图片
                    _buildImagePreview(_optionCImagePath, 'optionC'),
                    const SizedBox(height: 16),
                    
                    // 选项D
                    TextFormField(
                      controller: _optionDController,
                      decoration: const InputDecoration(
                        labelText: '选项D',
                        border: OutlineInputBorder(),
                        hintText: '请输入选项D',
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入选项D';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),
                    
                    // 选项D图片
                    _buildImagePreview(_optionDImagePath, 'optionD'),
                    const SizedBox(height: 16),
                    
                    // 正确答案
                    TextFormField(
                      controller: _correctAnswerController,
                      decoration: const InputDecoration(
                        labelText: '正确答案',
                        border: OutlineInputBorder(),
                        hintText: '请输入正确答案（A、B、C或D）',
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入正确答案';
                        }
                        if (!['A', 'B', 'C', 'D'].contains(value.toUpperCase())) {
                          return '正确答案必须是A、B、C或D';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    
                    // 解析
                    TextFormField(
                      controller: _explanationController,
                      decoration: const InputDecoration(
                        labelText: '解析（可选）',
                        border: OutlineInputBorder(),
                        hintText: '请输入题目解析',
                      ),
                      maxLines: 3,
                    ),
                    const SizedBox(height: 8),
                    
                    // 解析图片
                    _buildImagePreview(_explanationImagePath, 'explanation'),
                    const SizedBox(height: 24),
                    
                    // 保存按钮
                    ElevatedButton(
                      onPressed: _isLoading ? null : _saveQuestion,
                      child: _isLoading
                          ? const SizedBox(
                              height: 20,
                              width: 20,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : Text(isEditing ? '保存修改' : '添加题目'),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
  

}